//
//  LoopTarBar.swift
//  LoopWeibo
//
//  Created by loop安 on 2016/12/6.
//  Copyright © 2016年 loop. All rights reserved.
//

import UIKit

class LoopTarBar: UITabBar {
    
    var composeClosure: (()->())?
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.addSubview(composeBtn)
        composeBtn.addTarget(self, action: #selector(clickComposeBtn), for: UIControlEvents.touchUpInside)
    }
    
    //处理点击事件不应该在view中,故应使用闭包
    @objc private func clickComposeBtn() {
        print(#function)
        composeClosure?()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
//        print(self.subviews)
        super.layoutSubviews()
        
        let w = self.bounds.width / 5
        let h = self.bounds.height
        var index = 0
        for subview in self.subviews{
            if subview.isKind(of: NSClassFromString("UITabBarButton")!) {
                subview.frame = CGRect(x: w * CGFloat(index), y: 0, width: w, height: h)
                index += (index == 1 ? 2 : 1)
                
            }
        }
        //通过size和center去设置compose的位置
        composeBtn.bounds.size = CGSize(width: w, height: h)
        composeBtn.center = CGPoint(x: self.center.x, y: h / 2)
        
    }
    
    //懒加载compose按钮
    lazy var composeBtn: UIButton = {
        let btn = UIButton()
        btn.setBackgroundImage(#imageLiteral(resourceName: "tabbar_compose_button"), for: .normal)
        btn.setBackgroundImage(#imageLiteral(resourceName: "tabbar_compose_button_highlighted"), for: .highlighted)
        btn.setImage(#imageLiteral(resourceName: "tabbar_compose_icon_add"), for: .normal)
        btn.setImage(#imageLiteral(resourceName: "tabbar_compose_icon_add_highlighted"), for: .highlighted)
        return btn
    }()

}
